'use strict';

// const Controller = require('egg').Controller;

const Controller = require('./base');

class UserController extends Controller {

  // 用户列表
  async list() {
    const ctx = this.ctx;
    ctx.set('Content-Type', 'application/json');
    const user = await ctx.service.user.list(ctx.query);
    this.success(user);
  }

  // 用户详情
  async user() {
    const ctx = this.ctx;
    var params = ctx.params;
    ctx.set('Content-Type', 'application/json');
    if (!params.id) {
      this.ctx.throw(500, '参数错误');
    }
    const user = await ctx.service.user.find(params.id);
    this.success(user);
  }

  async create() {
    const ctx = this.ctx;
    var post = ctx.request.body;
    ctx.set('Content-Type', 'application/json');
    if (!post.name || !post.num) {
      this.ctx.throw(500, '参数错误');
    }
    // 如果给了ID，就是更新，没有则添加
    if (!post.id) {
      const user = await ctx.service.user.create(post);
      this.success(user);
    } else {
      const user = await ctx.service.user.update(post);
      this.success(user);
    }
  }

  async del() {
    const ctx = this.ctx;
    const id = ctx.request.body.id;
    ctx.set('Content-Type', 'application/json');
    console.log(id)
    const created = await ctx.service.user.del(id);
    this.success({
      msg: "删除成功"
    })
  }

}

module.exports = UserController;
